import {BaseApi} from "./BaseApi.ts";
import {buildPrepareBody, type PostParam, postParamToFormData, type UploadBody, type UploadError, uploadParamToFormData} from "../types/Post.ts";
import axios from "axios";
import {buildAttachThumbs} from "../types/Reply.ts";

export type PostAction = "new" | "modify" | "reply" | "quote"

export class PostApi extends BaseApi {
    prepare = (action: PostAction
        , fid?: number | undefined
        , stid?: number | undefined
        , tid?: number | undefined
        , pid?: number | undefined
        , comment?: 1 | undefined
    ) => this.instance.post("post.php", undefined, {
        params: {
            action, fid, stid, tid, pid, comment,
            __output: 8,
        }
    }).then(res => buildPrepareBody(res.data.data))


    sendPost = (
        action: PostAction
        , data: PostParam
        , fid?: number | undefined
        , stid?: number | undefined
        , tid?: number | undefined
        , pid?: number | undefined
        , comment?: 1 | undefined
    ) => this.instance.post("post.php", postParamToFormData(data), {
        headers: {'Content-Type': 'multipart/form-data'},
        params: {
            action, fid, stid, tid, pid, comment,
            __output: 8,
            step: 2,
        }
    }).then(res => res.data.data)

    // 上传附件
    attachUpload = (url: string, auth: string, fid: number, file: File) => axios.post<UploadBody>(url,
        uploadParamToFormData(auth, fid, file),
        {
            headers: {'Content-Type': 'multipart/form-data'},
            timeout: 60 * 1000,
            // timeout: 10 * 1000,
        }
    ).then(res => {
        if (res.data.error_code) {
            return Promise.reject({
                file,
                code: res.data.error_code,
                error: res.data.error,
                message: res.data.error_txt
            } as UploadError)
        }


        res.data.file = file
        res.data.blob = window.URL.createObjectURL(file);
        res.data.thumbs = buildAttachThumbs(res.data.url, res.data.thumb)
        return res
    })

    // 删除附件
    attachDel = (filename: string, tid: number, pid?: number | undefined) => this.instance.post("nuke.php", undefined, {
        params: {
            func: "delattach",
            __output: 11,
            aid: filename,
            tid,
            pid,
        }
    })
}